﻿using AutoMapper;
using MediatR;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.Api.Application.hqApplication.Commands.Enterprisess;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.RBAC.Api.Application.hqApplication.Commands.Departmentss
{
    public class AddDepartmentHander : IRequestHandler<AddDepartmentCommand, Result>
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 企业仓储
        /// </summary>
        private readonly IBaseRepository<Departments> departmentrepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="departmentrepository"></param>
        public AddDepartmentHander(IMapper mapper, IBaseRepository<Departments> departmentrepository)
        {
            this.mapper = mapper;
            this.departmentrepository = departmentrepository;
        }

        /// <summary>
        /// 部门添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(AddDepartmentCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                Departments entity = mapper.Map<Departments>(request);
                var res = await departmentrepository.Add(entity);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "添加部门成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "添加部门异常" + ex.Message;
            }
            return result;
        }
    }
}
